package com.runmi.webchat.aftersale.web.api.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.runmi.webchat.aftersale.common.result.Result;
import com.runmi.webchat.aftersale.common.result.ResultFactory;
import com.runmi.webchat.aftersale.common.utils.StringUtil;
import com.runmi.webchat.aftersale.dbcore.dao.MemberInfoDao;
import com.runmi.webchat.aftersale.dbcore.entity.MemberInfo;
import com.runmi.webchat.aftersale.dbcore.mapper.MemberInfoMapper;
import com.runmi.webchat.aftersale.util.WxUtil;
import com.runmi.webchat.aftersale.web.api.vo.UserAccessTockenVo;
import com.runmi.webchat.aftersale.web.api.vo.UserInfoVo;
import com.runmi.webchat.aftersale.web.base.BaseController;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Controller
@RequestMapping(value = "/webchatapi/register")
public class RegisterController extends  BaseController{

	@Autowired
	private MemberInfoDao memberInfoDao;
	
	@Autowired
	private MemberInfoMapper memberInfoMapper;
	
	 @Autowired
	 private WxUtil wxUtil;
	
	@ApiOperation(value = "保存会员信息", notes = "保存会员信息 ",tags={ "微信API", })
	  @RequestMapping(value = "/save")
	  @ResponseBody
	  public Result queryProvinceRegions(
			  HttpServletRequest request,HttpServletResponse response,
	          @ApiParam(value = "mobile",required = true)@RequestParam(value = "mobile") String mobile,
	          @ApiParam(value = "realName",required = true)@RequestParam(value = "realName") String realName,
	          @ApiParam(value = "sex",required = false)@RequestParam(value = "sex") Byte sex,
	          @ApiParam(value = "birthday",required = false)@RequestParam(value = "birthday") String birthday
	          ) throws Exception, IOException{
		Result result=ResultFactory.getResultFail();
		
		if(StringUtil.isBlank(mobile)){
			return ResultFactory.getResultFail("手机号码不能为空");
		}
		String openId= this.readCokie(request, response, "openId");
		String imageUrl="";
		String nickName="";
		if(StringUtil.isNotEmptyStr(openId)){
			MemberInfo memberInfo= memberInfoDao.getMemberInfoByOpenId(openId);
			if(null!=memberInfo){
				return ResultFactory.getResultFail("您已经登记过");
			}
			imageUrl=this.readCokie(request, response, "imageUrl");
			nickName=this.readCokie(request, response, "nickName");
			
		}
		
		MemberInfo memberInfo= memberInfoDao.getMemberInfoByMobile(mobile);
		if(null!=memberInfo){
			return ResultFactory.getResultFail("手机号码已经登记过");
		}
		this.log.info("birthday:" + birthday + " sex:" + sex +  " realName:" + realName + " mobile:" + mobile);
		
		MemberInfo record=new MemberInfo();
		record.setMobile(mobile);
		record.setOpenId(openId);
		record.setRealName(realName);
		record.setSex(sex);
		record.setImageUrl(imageUrl);
		record.setNickName(nickName);
		record.setBirthday(birthday);
		record.setCreateTime(new Date());
		memberInfoMapper.insert(record);		
		return  ResultFactory.getResultSuccess();
	  }
	
	private String GLCP_BACK_URL_HOST="https://ljh.rc288.com/after/";
	
	 @ApiOperation(value = "获取用户信息", notes = "先重定向到微信获取到openID以后重定向到backUrl",tags={ "微信API", })
	   
	 
	 @RequestMapping(value = "/queryUserInfo", produces = { "application/json" },method = RequestMethod.GET)
	    public ModelAndView queryUserInfo( HttpServletRequest request,
	            HttpServletResponse response ) throws ServletException, IOException {
	        //log.info("appkey:{"+appkey+"}, backUrl:{"+backUrl+"}");
	        ModelAndView mav = new ModelAndView();
	       
	        String wxBackUrl=java.net.URLEncoder.encode(GLCP_BACK_URL_HOST +"webchatapi/register/getUserCallBack","utf-8");
	        String wxUrl= wxUtil.getRequestCodeUrl(wxBackUrl,"1");
	        log.info("-------wxUrl:{"+wxUrl+"}, wxBackUrl:{"+wxBackUrl+"}");
	      //  this.writeCokie(request,response,"backUrl",url,1000*60*10);
	        return  new ModelAndView(new RedirectView(wxUrl));
	        //return new ModelAndView("redirect:/" + wxUrl);
	    }



	    @ApiOperation(value = "微信回调详细用户信息", notes = "微信回调",tags={ "微信API", })
	    @RequestMapping(value = "/getUserCallBack", produces = { "application/json" },method = RequestMethod.GET)
	    public void getUserCallBack(
	            HttpServletRequest request,
	            HttpServletResponse response,
	            @ApiParam(value = "code") @RequestParam(value = "code", required = false)String code) throws ServletException, IOException {
	        ModelAndView mav = new ModelAndView();
	       
	        UserAccessTockenVo accessTockenVo=wxUtil.getUserOpenId(code);
	     
	        UserInfoVo userInfoVo= wxUtil.getUserInfo(accessTockenVo.getAccess_token(),accessTockenVo.getOpenid());
	        String url= java.net.URLDecoder.decode("https://ljh.rc288.com/member/register.html","utf-8");

	        String nickname= java.net.URLEncoder.encode(userInfoVo.getNickname(),"utf-8");
	        String headimgurl= java.net.URLEncoder.encode(userInfoVo.getHeadimgurl(),"utf-8");

	        this.writeCokie(request, response, "openId", userInfoVo.getOpenid(), 0);
	        this.writeCokie(request, response, "nickname", nickname, 0);
	        this.writeCokie(request, response, "headimgurl", headimgurl, 0);
	

	        log.info("code:" + code + " backUrl:" + url);
	        response.sendRedirect(url);
	        //  return  new ModelAndView(new RedirectView(url));
	        //return urlBack;
	    }
}
